<template>
  <view class="page">
    <status-bar backgroundColor="rgb(255, 255, 255)"></status-bar>
    <uni-nav-bar leftWidth="0" rightWidth="0" :border="false" background-color="rgb(255, 255, 255)">
      <view class="nav-bar">
        <view @click="navBack()">
          <uni-icons type="left" size="27"/>
        </view>
        <view class="name">房间管理</view>
        <view @click="clickRight" class="edit">{{ editMode ? '完成' : '编辑' }}</view>
      </view>
    </uni-nav-bar>
    <scroll-view :scroll-top="scrollTop" scroll-y="true" class="list" @scroll="scroll">
      <view class="__margin-top"></view>
      <view class="drag-sort-wrap">
        <dragSort :list="rooms" :disabled="editMode" @delclick="tryDeleteRoom" @change="sortChange"
                  @childClick="clicklistitem" @complete="reSort">
          <template v-slot="{ item,delClick }">
            <view class="item">
              <uni-icons v-if="editMode" class="icon" type="minus-filled" size="50rpx" @click="delClick(item)"/>
              <view class="content">
                <text class="name">{{ item.name_room }}</text>
                <text class="describe">{{ item.equip_total }}个设备</text>
              </view>
              <view class="touch-tight">
                <uni-icons v-if="!editMode" type="right" size="30rpx"></uni-icons>
                <uni-icons v-if="editMode" type="bars" size="30rpx"></uni-icons>
              </view>
            </view>
          </template>
        </dragSort>
      </view>
      <view class="__margin-top"></view>
    </scroll-view>


    <view class="add_room" v-if="!editMode">
      <uni-icons type="plus-filled" size="100rpx" color="#428d86" @click="navTo('/pages/roomadd/roomadd')"/>
    </view>

  </view>
</template>

<script>
import SeniorTable from '@/components/data-table/senior-table.vue'

//获取用户所有房间列表接口
import {
  _getrooms
} from '@/service/room.js'
import {
  _deleterooms
} from '@/service/room.js'
import dragSort from '@/components/boom-drag-sort/index.vue'
import {_getChartData} from "../../service/exper_api";
import {_changeRoomOrder} from "../../service/room";
import UniNavBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue";
import StatusBar from "@/components/status-bar/status-bar.vue";
import UniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";

export default {
  components: {
    UniIcons,
    StatusBar,
    UniNavBar,
    SeniorTable,
    dragSort
  },
  data() {
    return {
      scrollTop: 0,
      old: {
        scrollTop: 0
      },
      editMode: false,
      serialnum_room: '',
      nickname: '',
      account_user: '',
      rooms: [],
      pairs: [],
    };
  },
  onLoad() {
    let newdata;
    try {
      const value = uni.getStorageSync('userInfo');
      if (value != null) {
        this.nickname = value.nickname
        this.account_user = value.accountNum
      }
    } catch (e) {
      console.error(e);
    }
  },
  onShow() {
    if (this.editMode != true) {
      this.getrooms();
    }
  },
  methods: {
    scroll(e) {
      // console.log(e)
      this.old.scrollTop = e.detail.scrollTop
    },
    async changeOrder(data) {
      let resultData;
      try {
        resultData = await _changeRoomOrder({
          data
        });
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置roomsguanli.vue : changeOrder");
      }
      return resultData.message;
    },
    reSort(list) {
      try {
        const affectedRange = this.affectedRange();
        console.log(affectedRange);
        const originalSlice = this.rooms.slice(0, affectedRange[1] + 1);
        const targetSlice = list.slice(0, affectedRange[1] + 1).sort((a, b) => a.index - b.index);

        this.changeOrder(this.findSwaps(originalSlice, targetSlice)).then((res) => {
          console.log(res);
        });
      } catch (error) {
        console.error("reSort 错误:", error);
      }
    },
    affectedRange() {
      try {
        let minRange = Infinity;
        let maxRange = -Infinity;
        this.pairs.forEach(([start, end]) => {
          if (start < minRange) minRange = start;
          if (end > maxRange) maxRange = end;
        });
        return [minRange, maxRange];
      } catch (error) {
        console.error("affectedRange 错误:", error);
        return [0, 0]; // 默认返回值
      }
    },
    findSwaps(original, target) {
      const swaps = [];
      const valueToIndex = new Map();
      const indexToValue = new Map();
      // Initialize maps
      original.forEach((value, index) => {
        valueToIndex.set(value.serialnum_room, index);
        indexToValue.set(index, value.serialnum_room);
      });

      for (let i = 0; i < original.length; i++) {
        const value = indexToValue.get(i);
        const targetValue = target[i].serialnum_room;
        if (value != targetValue) {
          const targetIndex = valueToIndex.get(targetValue);
          if (targetIndex !== undefined && targetIndex !== i) {
            swaps.push([value, target[i].serialnum_room]);
            valueToIndex.set(value, targetIndex);
            valueToIndex.set(targetValue, i);
            indexToValue.set(i, targetValue);
            indexToValue.set(targetIndex, value);
          }
        }
      }
      console.log(swaps)
      return swaps;
    },
    sortChange(e) {
      const newPair = [e.originalPosition, e.finalPosition].sort();
      this.pairs.push(newPair);
      // console.log(e,this.pairs);
    },
    clickRight() {
      this.editMode = !this.editMode;
    },
    navTo(url) {
      this.add = true;
      uni.navigateTo({
        url: url,
        success(res) {
          console.log('成功啦', res);
        },
        fail(err) {
          console.log('失败啦', err);
        }
      })
    },
    async getrooms() {
      try {
        let data = {
          account_user: this.account_user
        }
        let res = await _getrooms(data);
        this.rooms = res.data;
        console.log(this.rooms);
      } catch (e) {
        console.log(e)
      }
    },
    navBack() {
      uni.navigateBack();
    },
    async deleteRoom(serialnum_room) {
      let resultData;
      try {
        resultData = await _deleterooms(serialnum_room);
        // console.log(resultData)
      } catch (error) {
        throw error; //抛出异常
      }
      if (resultData === undefined || resultData.status !== 200) {
        throw new Error("接口返回异常，位置roomsguanli.vue : deleteRoom");
      }
      return resultData;
      // if (res.flag) {
      //   setTimeout(() => {
      //     uni.hideLoading();
      //   }, 500);
      // } else {
      //   setTimeout(() => {
      //     uni.hideLoading();
      //     this.$api.msg(data.message);
      //   }, 500);
      // }
      // this.rooms.splice(this.deleteIndex, 1); // 直接删除要删除的数据

    },
    tryDeleteRoom(item) {
      console.log(item);
      uni.showModal({
        title: '提示',
        content: '是否删除此房间',
        success: (res) => {
          if (res.confirm) {
            console.log('用户点击确定');
            this.deleteRoom(item.serialnum_room).then((res) => {
              if (res.message === '删除成功') {
                this.rooms.splice(item.index, 1); // 直接删除要删除的数据
              } else {
                this.$api.msg(res.message);
              }
            });
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        },
        fail: (err) => {

        }
      });
    },
    clicklistitem(item) {
      if (this.editMode != true) {
        uni.navigateTo({
          url: `/pages/roomedit/roomedit?roomName=${item.name_room}&roomSerialnum=${item.serialnum_room}&accountNum=${this.account_user}`
        });
      }
    }
  }
}
</script>

<style scoped lang="scss">
.page {
  height: 100vh;
  background-color: #e5e5e569;
}

.list {
  //#ifdef APP-PLUS
  height: calc(100vh - var(--status-bar-height) - 44px);
  //#endif
  //#ifdef H5
  height: calc(100vh - 44px);
  //#endif
}

.__margin-top {
  height: 30rpx;
}

.drag-sort-wrap {
  box-sizing: border-box;
  padding: 0 30rpx;
}

.item {
  width: 100%;
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: rgba(255, 255, 255, 0); // 设置背景色

  .icon {
    margin-right: 20rpx;
  }

  .touch-tight {
    width: 24px;
    height: 24px;
    margin-left: auto;
  }

  .content {
    display: flex;
    flex-direction: column;
    margin-left: 30rpx;

    .name {
      font-size: 34rpx;
    }

    .describe {
      font-size: 25rpx;
      color: #808080;
    }
  }
}

.nav-bar {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .name {
    font-size: medium;
    font-weight: 500;
  }

  .edit {
    color: #428d86;
    font-size: 26rpx;
  }
}

.add_room {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
}
</style>